package com.matace.keychain.presentation.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.matace.keychain.domain.LoginUseCase;

/**
 * 登录界面的ViewModel
 * 负责处理登录相关的业务逻辑和UI状态管理
 */
public class LoginViewModel extends ViewModel {
    private final LoginUseCase loginUseCase;
    // 用户名输入框的数据
    private final MutableLiveData<String> username = new MutableLiveData<>("");
    // 密码输入框的数据
    private final MutableLiveData<String> password = new MutableLiveData<>("");
    // 记住登录状态的数据
    private final MutableLiveData<Boolean> rememberMe = new MutableLiveData<>(false);
    // 登录成功状态的数据
    private final MutableLiveData<Boolean> loginSuccess = new MutableLiveData<>();
    // 登录错误信息的数据
    private final MutableLiveData<String> loginError = new MutableLiveData<>("");

    /**
     * 构造函数
     * @param loginUseCase 登录用例
     */
    public LoginViewModel(LoginUseCase loginUseCase) {
        this.loginUseCase = loginUseCase;
        // 如果之前选择了记住登录，则自动填充保存的用户名和密码
        if (loginUseCase.isRememberMe()) {
            username.setValue(loginUseCase.getSavedUsername());
            password.setValue(loginUseCase.getSavedPassword());
            rememberMe.setValue(true);
        }
    }

    // Getter方法
    public LiveData<String> getUsername() { return username; }
    public LiveData<String> getPassword() { return password; }
    public LiveData<Boolean> getRememberMe() { return rememberMe; }
    public LiveData<Boolean> getLoginSuccess() { return loginSuccess; }
    public LiveData<String> getLoginError() { return loginError; }

    // Setter方法
    public void setUsername(String value) { username.setValue(value); }
    public void setPassword(String value) { password.setValue(value); }
    public void setRememberMe(boolean value) { rememberMe.setValue(value); }

    public void login() {
        String user = username.getValue() != null ? username.getValue().trim() : "";
        String pass = password.getValue() != null ? password.getValue().trim() : "";
        if (user.isEmpty() || pass.isEmpty()) {
            loginError.setValue("请输入用户名和密码");
            loginSuccess.setValue(false);
            return;
        }
        if (loginUseCase.login(user, pass)) {
            if (Boolean.TRUE.equals(rememberMe.getValue())) {
                loginUseCase.saveCredentials(user, pass);
            } else {
                loginUseCase.clearCredentials();
            }
            loginSuccess.setValue(true);
        } else {
            loginError.setValue("用户名或密码错误");
            loginSuccess.setValue(false);
        }
    }
}